package com.yixun.service.impl;

import com.alibaba.fastjson.JSON;
import com.yixun.entity.YxDept;
import com.yixun.entity.YxUser;
import com.yixun.mapper.DeptMapper;
import com.yixun.service.DeptService;
import com.yixun.service.LogSetService;
import com.yixun.service.RedisService;
import com.yixun.service.YwDiQuService;
import com.yixun.util.LogUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DeptServiceImpl implements DeptService {
    private final DeptMapper deptMapper;
    private final YwDiQuService ywDiQuService;
    private final RedisService redisService;
    private final LogSetService logSetService;

    public DeptServiceImpl(DeptMapper deptMapper, YwDiQuService ywDiQuService, RedisService redisService, LogSetService logSetService) {
        this.deptMapper = deptMapper;
        this.ywDiQuService = ywDiQuService;
        this.redisService = redisService;
        this.logSetService = logSetService;
    }


    @Override
    public String getDeptTree(String dept_id) {
        List<YxDept> all_list = deptMapper.getAllDeptList();
        YxDept dept = deptMapper.getDeptBean(dept_id);
        if (null != dept) {
            String json_str = "[{\"id\":" + dept.getDept_id() + ",\"text\":\""
                    + dept.getDept_name()+ "\",\"attributes\":{}";
            String child_str = getAllDeptTreeHandle(all_list,getChildDeptListByID(all_list,dept.getDept_id()+""));
            if (null != child_str && !"".equals(child_str)) {
                json_str += ",\"children\":[" + child_str + "]";
            }
            json_str += "}]";
            return json_str;
        }else {
            return "[]";
        }
    }

    @Override
    public List<YxDept> getChildDeptListByID(String dept_id) {
        List<YxDept> all_list = deptMapper.getAllDeptList();
        List<YxDept> child_dept_list = new ArrayList<>();
        for (YxDept dept: all_list) {
            if (dept_id.equals(dept.getParent_id() + "")) {
                dept.setDq_yw_name(ywDiQuService.getDqNameByDqYwId(dept.getDq_yw_id()));
                child_dept_list.add(dept);
            }
        }
        return child_dept_list;
    }

    @Override
    @Transactional
    public int insertDept(YxUser sessionUser, YxDept dept) {
        int row;
        YxDept parentDept = deptMapper.getDeptBean(dept.getParent_id() + "");
        Long dept_id = redisService.incr("dept_id", 1L);
        dept.setDept_id(dept_id);
        dept.setTree_position(parentDept.getTree_position() + dept_id + "$");
        row = deptMapper.insertDept(dept);
        if (row == 1) {
            logSetService.insertSettingLogs(LogUtil.ADD, "部门", JSON.toJSONString(dept), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    public YxDept getDeptBean(String dept_id) {
        return deptMapper.getDeptBean(dept_id);
    }

    @Override
    @Transactional
    public int updateDept(YxUser sessionUser, YxDept dept) {
        int row;
        row = deptMapper.updateDept(dept);
        if (row == 1) {
            logSetService.insertSettingLogs(LogUtil.UPDATE, "部门", JSON.toJSONString(dept), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int delDept(YxUser sessionUser, String id) {
        int row = 0;
        String[] ids = id.split(",");
        for (String dept_id: ids) {
            String tree_position = deptMapper.getTreePositionByDeptId(dept_id);
            deptMapper.delDeptAndChild(tree_position);
            row++;
        }
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.DELETE,"部门", JSON.toJSONString(id), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int moveDept(YxUser sessionUser, String parent_id, String dept_ids) {
        int row = 0;
        String parent_dept_position = deptMapper.getTreePositionByDeptId(parent_id);
        if (null != dept_ids && !"".equals(dept_ids)) {
            String[] ids = dept_ids.split(",");
            for (String dept_id: ids) {
                moveDeptHandle(dept_id, parent_id, parent_dept_position);
                row++;
            }
        }
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.MOVE,"部门", JSON.toJSONString(parent_id + "--" + dept_ids), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int sortDept(YxUser sessionUser, String id) {
        int row = 0;
        String[] ids = id.split(",");
        Map<String,String> m = new HashMap<>();
        for (int i = 0;i < ids.length; i++) {
            m.put("dept_id", ids[i]);
            m.put("sort_id", (i+1) + "");
            deptMapper.sortDept(m);
            row++;
        }
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.SAVE_SORT,"部门", JSON.toJSONString(id), sessionUser);
            return row;
        }
        return row;
    }

    /*=======================================moveDeptHandle===============================================*/

    public void moveDeptHandle(String dept_id, String parent_id, String parent_dept_position){
        String dept_position = parent_dept_position + dept_id + "$";
        Map<String, String> map = new HashMap<>();
        map.put("dept_id", dept_id);
        map.put("parent_id", parent_id);
        map.put("tree_position", dept_position);

        if (deptMapper.moveDept(map) > 0) {
            // 该节点下的子节点一并转移
            List<YxDept> child_list = getChildDeptListByID(dept_id);
            if (null != child_list && child_list.size() > 0) {
                for (YxDept child: child_list) {
                    moveDeptHandle(child.getDept_id()+"", dept_id, dept_position);
                }
            }
        }

    }

    /*=======================================moveDeptHandle===============================================*/


    /*=======================================Dept_Tree_Util===============================================*/

    public List<YxDept> getChildDeptListByID(List<YxDept> all_list, String dept_id){
        List<YxDept> child_dept_list = new ArrayList<>();
        for (YxDept dept: all_list) {
            if (dept_id.equals(dept.getParent_id() + "")) {
                child_dept_list.add(dept);
            }
        }
        return child_dept_list;
    }

    public String getAllDeptTreeHandle(List<YxDept> all_list, List<YxDept> dl){
        String json_str = "";
        if (null != dl && dl.size() > 0) {
            for (YxDept dept: dl) {
                json_str += ",{";
                json_str += "\"id\":" + dept.getDept_id() + ","
                        + "\"text\":\"" + dept.getDept_name()
                        + "\",\"attributes\":{}";
                List<YxDept> child_d_list = getChildDeptListByID(all_list, dept.getDept_id() + "");
                if (null != child_d_list && child_d_list.size() > 0) {
                    json_str +=",\"children\":["+ getAllDeptTreeHandle(all_list,child_d_list) + "]";
                }
                json_str += "}";
            }
            if (!"".equals(json_str)) {
                json_str = json_str.substring(1);
            }
        }
        return json_str;
    }

    /*=======================================Dept_Tree_Util===============================================*/
}
